package com.example.week1_day04_2;


import com.example.week1_day04_2.entity.Movie;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Spring MVC ->后端接口
 */
@RestController
@RequestMapping("api")
public class MovieController {

    /**
     * get请求
     * @return
     */

    @GetMapping("/movie/")
    public ResponseEntity<List<Movie>> query(){
        //暂时还没有链接数据库，造一个假的movie
       Movie m1 = new Movie(1,"肖申克的救赎","导演","美国",9.7,"励志，救赎");
       Movie m2 = new Movie(2,"霸王别姬","凯哥","中国",9.7,"励志，救赎");
       return ResponseEntity.ok(Arrays.asList(m1,m2));
    }

    /**
     * 请求 {}=>@PathVariable
     * @param index
     * @return
     */
    @GetMapping("/movie/{index}")
    public ResponseEntity<Movie> queryById(@PathVariable("index") Integer index){
        //暂时还没有链接数据库，造一个假的movie
        Movie m1 = new Movie(1,"肖申克的救赎","导演","美国",9.7,"励志，救赎");
        Movie m2 = new Movie(2,"霸王别姬","凯哥","中国",9.7,"励志，救赎");
        List<Movie> list = Arrays.asList(m1,m2);
        Movie result = null;
        for (Movie m : list) {
            if(m.getIndex().equals(index)){
               result=m;
               break;
            }
        }
        return ResponseEntity.ok(result);
    }


    /**
     * post请求
     * 注意: @RequestBody Movie movie =》json
     * @return
     */
    @PostMapping("/movie")
    public ResponseEntity<Void> add(@RequestBody Movie movie){
        System.out.println(movie);
        //后续 -》保存到数据库
        return ResponseEntity.ok(null);
    }

    /**
     * put请求
     * @return
     */
    @PutMapping("/movie/{index}")
    public ResponseEntity<Movie> update(@PathVariable("index") Integer index,@RequestBody Movie movie){
        Movie m1 = new Movie(1,"肖申克的救赎","导演","美国",9.7,"励志，救赎");
        Movie m2 = new Movie(2,"霸王别姬","凯哥","中国",9.7,"励志，救赎");
//        List<Movie> list = Arrays.asList(m1,m2);
        List<Movie> list = new ArrayList<>();
        list.add(m1);
        list.add(m2);
        for (int i = 0;i<list.size() ; i++) {
            Movie m = list.get(i);
            if(m.getIndex().equals(index)){
                list.remove(i);
                list.add(i,movie);
                System.out.println(list);
                return ResponseEntity.ok(movie);
            }
        }

        return ResponseEntity.ok(null);
    }

    /**
     * delete请求
     * @return
     */
    @DeleteMapping("/movie/{index}")
    public ResponseEntity<Void> delete(@PathVariable("index") Integer index){
        System.out.println(index);
        //后续 -》保存到数据库
        return ResponseEntity.ok(null);
    }

}
